import 'package:demo/constants/app_icon.dart';
import 'package:demo/provider/view_model/cate_view_model.dart';
import 'package:demo/provider/widget/base_provider_widget.dart';
import 'package:flutter/material.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({Key? key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  /// view model
  late final CateViewModel _cateViewModel = CateViewModel();

  /// 滚动控制器
  // 左侧的控制器
  late final ScrollController _rightScrollController = ScrollController()..addListener(_onRightScrollListener);

  // 顶部一级分类控制器
  late final ScrollController _scrollController = ScrollController();

  /// 动画控制器
  /// 控制字体缩放的
  late final AnimationController _textScaleAnimationController =
      AnimationController(duration: const Duration(milliseconds: 300), vsync: this);

  /// 控制分类移动size高度的
  late final AnimationController _sizeAnimationController =
      AnimationController(duration: const Duration(milliseconds: 300), vsync: this);

  /// 字体scale的动画属性
  late final Animation<double> _textScaleAnimation = Tween<double>(begin: 1.0, end: 1.2).animate(
    CurvedAnimation(parent: _textScaleAnimationController, curve: Curves.linear),
  );

  /// 分类移动container size高度的动画属性
  late final Animation<double> _categorySizeAnimation = Tween<double>(begin: 1.0, end: 0.48).animate(
    CurvedAnimation(parent: _sizeAnimationController, curve: Curves.linear),
  );

  /// 分类图片size高度的动画属性,以及fade效果
  late final Animation<double> _categoryPictureAnimation = Tween<double>(begin: 1.0, end: 0).animate(
    CurvedAnimation(parent: _sizeAnimationController, curve: Curves.linear),
  );
  late final Animation<double> _categoryPictureFadeAnimation = Tween<double>(begin: 1.0, end: 0).animate(
    CurvedAnimation(parent: _sizeAnimationController, curve: Curves.linear),
  );

  /// 滚动执行逻辑锁
  bool _rightScrollLock = false;

  @override
  void dispose() {
    _scrollController.dispose();
    _rightScrollController.dispose();
    _textScaleAnimationController.dispose();
    _cateViewModel.dispose();
    super.dispose();
  }

  /// 右边的滑块滚动监听
  void _onRightScrollListener() async {
    if (_rightScrollLock) return;
    // 滚动大于44像素并且动画没有执行的执行一次动画
    if (_rightScrollController.offset > 44) {
      if (_sizeAnimationController.value != 1) {
        _rightScrollLock = true;
        await _sizeAnimationController.forward();
        _rightScrollLock = false;
      }
    } else {
      /// 反向如果动画执行过就还原
      if (_sizeAnimationController.value == 1) {
        _rightScrollLock = true;
        await _sizeAnimationController.reverse();
        _rightScrollLock = false;
      }
    }
  }

  /// 点击顶上分类的内容
  void _onCategoryBarClickListener(int index) async {
    if (index != _cateViewModel.categoryIndex) {
      _cateViewModel.categoryIndex = index;
      // 滚动对应的item项目,执行跳动左侧文字缩放动画
      await _scrollController.animateTo(
        72.0 * index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.fastOutSlowIn,
      );
      await _textScaleAnimationController.forward();
      await _textScaleAnimationController.reverse();
    }
  }

  /// 左边
  void _onLeftItemClickListener(int index) async {
    if (index != _cateViewModel.leftCategoryIndex) {
      _cateViewModel.leftCategoryIndex = index;
    }
    // 执行跳动左侧文字缩放动画
    await _textScaleAnimationController.forward();
    await _textScaleAnimationController.reverse();
  }

  /// 构建顶部appbar
  PreferredSizeWidget get _buildHeader {
    return AppBar(
      elevation: 0.5,
      backgroundColor: Colors.grey[100],
      title: _buildSearchBar,
      toolbarHeight: 48,
    );
  }

  /// 构建搜索框
  Widget get _buildSearchBar {
    return Container(
      alignment: Alignment.centerLeft,
      height: 32,
      padding: const EdgeInsets.only(left: 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: Colors.grey[200],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: const [
          Icon(search, size: 18, color: Colors.black),
          Padding(
            padding: const EdgeInsets.only(left: 5),
            child: Text(
              "请输入搜索商品关键字",
              style: TextStyle(fontSize: 14, color: Color(0xFF3A3C42)),
            ),
          )
        ],
      ),
    );
  }

  /// 构建搜索框下的滑动bar
  Widget get _buildCategoryBarSelector {
    final double itemW = MediaQuery.of(context).size.width / 5;
    return AnimatedBuilder(
      animation: _sizeAnimationController,
      builder: (BuildContext context, Widget? child) {
        return SizeTransition(axis: Axis.vertical, sizeFactor: _categorySizeAnimation, child: child);
      },
      child: SizedBox(
        height: 72,
        child: Selector<CateViewModel, List<String>>(
          builder: (BuildContext context, List<String> data, Widget? child) {
            return ListView.builder(
              controller: _scrollController,
              scrollDirection: Axis.horizontal,
              itemCount: data.length,
              itemBuilder: (BuildContext _, int i) => _buildCategoryItemSelector(data[i], i, itemW),
              itemExtent: 72,
            );
          },
          selector: (BuildContext p1, CateViewModel p2) => p2.categoryData,
        ),
      ),
    );
  }

  /// 构建左侧的缩放文字
  Widget _buildCategoryItemSelector(String itemData, int i, double itemW) {
    return GestureDetector(
      onTap: () => _onCategoryBarClickListener(i),
      child: Container(
        width: itemW,
        color: Colors.grey[100],
        child: Selector<CateViewModel, int>(
          shouldRebuild: (int previous, int next) {
            return previous == i || next == i;
          },
          builder: (BuildContext context, int categoryIndex, Widget? child) {
            final Widget titleLayout = Text(itemData, maxLines: 1, style: const TextStyle(fontSize: 12));
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                AnimatedBuilder(
                  animation: _sizeAnimationController,
                  child: Center(
                    child: Container(
                      height: 36,
                      width: 36,
                      margin: const EdgeInsets.only(bottom: 8),
                      child: CircleAvatar(
                        backgroundImage: NetworkImage(
                          "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=221169056,4042812421&fm=26&gp=0.jpg",
                        ),
                      ),
                    ),
                  ),
                  builder: (BuildContext context, Widget? child) {
                    return SizeTransition(
                      axis: Axis.vertical,
                      sizeFactor: _categoryPictureAnimation,
                      child: FadeTransition(opacity: _categoryPictureFadeAnimation, child: child),
                    );
                  },
                ),
                AnimatedCrossFade(
                  firstChild: titleLayout,
                  secondChild: Container(
                    padding: const EdgeInsets.only(left: 8, right: 8),
                    decoration: BoxDecoration(color: Colors.pinkAccent, borderRadius: BorderRadius.circular(8)),
                    child: titleLayout,
                  ),
                  crossFadeState: categoryIndex != i ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                  duration: const Duration(milliseconds: 300),
                ),
              ],
            );
          },
          selector: (BuildContext p1, CateViewModel p2) => p2.categoryIndex,
        ),
      ),
    );
  }

  /// 构建左边的list view
  Widget get _buildLeftListSelector {
    return Selector<CateViewModel, List<String>>(
      builder: (BuildContext context, List<String> value, Widget? child) {
        return ListView.builder(
          itemCount: value.length,
          itemExtent: 55,
          itemBuilder: (BuildContext context, int position) {
            return GestureDetector(
              onTap: () => _onLeftItemClickListener(position),
              child: _buildLeftScaleItem(value[position], position),
            );
          },
        );
      },
      selector: (BuildContext p1, CateViewModel p2) => p2.leftCategoryData,
    );
  }

  /// 构建左侧的缩放文字
  Widget _buildLeftScaleItem(String text, int i) {
    return Selector<CateViewModel, int>(
      shouldRebuild: (int p, int n) {
        return p == i || n == i;
      },
      builder: (BuildContext context, int value, Widget? child) {
        Color bgColor = Color(0xFFF5F5F5);
        Color textColor = Color(0xFF666666);
        FontWeight? fontWeight;
        Widget textLayout;

        /// 只给选中的上
        if (value == i) {
          bgColor = Colors.white;
          textColor = Color(0xFF333333);
          fontWeight = FontWeight.w700;

          /// 动画
          textLayout = AnimatedBuilder(
            animation: _textScaleAnimationController,
            child: Text(
              text,
              maxLines: 1,
              style: TextStyle(color: textColor, fontSize: 14, fontWeight: fontWeight),
            ),
            builder: (BuildContext context, Widget? child) {
              return ScaleTransition(
                alignment: Alignment.center,
                scale: _textScaleAnimation,
                child: child,
              );
            },
          );
        } else {
          textLayout = Text(
            text,
            maxLines: 1,
            style: TextStyle(color: textColor, fontSize: 14, fontWeight: fontWeight),
          );
        }
        return Container(
          height: 55,
          alignment: Alignment.center,
          color: bgColor,
          child: textLayout,
        );
      },
      selector: (BuildContext p1, CateViewModel p2) => p2.leftCategoryIndex,
    );
  }

  /// 构建右边的List
  Widget get _buildRightListSelector {
    return GridView.builder(
      controller: _rightScrollController,
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200.0,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
        childAspectRatio: 4.0,
      ),
      itemBuilder: (BuildContext context, int index) {
        return Container(
          alignment: Alignment.center,
          color: Colors.teal[100 * (index % 9)],
          child: Text('grid item $index'),
        );
      },
      itemCount: 50,
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BaseProviderWidget<CateViewModel>(
      viewModel: _cateViewModel,
      child: Scaffold(
        appBar: _buildHeader,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildCategoryBarSelector,
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(width: 98, color: Colors.grey[100], child: _buildLeftListSelector),
                  Expanded(
                    child: _buildRightListSelector,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
